package lumis.service.wsrp.producer;

import java.util.Arrays;
import java.util.Date;

import javax.persistence.NoResultException;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.TabularSource;
import lumis.doui.source.field.ITabularSourceField;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;
import lumis.service.wsrp.common.WSRPUtils;

import com.sun.portal.wsrp.common.LeaseTime;

/**
 * {@link ProcessActionHandler} responsible for persisting a new
 * {@link RemoteConsumerRegistration} to be associated with the current service instance.
 * 
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class OutbandRegistrationInterfaceProcessActionHandler extends ProcessActionHandler<TabularSource<ITabularSourceField>>
{
	public void processAction() throws PortalException
	{
		Object portletModes = getParameter("consumerModes");
		if(portletModes == null){
			throw new PortalException("EMPTY_PORTLET_MODES", getResource());
		}
		Object windowStates = getParameter("consumerWindowStates");
		if(windowStates == null){
			throw new PortalException("EMPTY_WINDOW_STATES", getResource());
		}
		
		RemoteConsumerRegistration registration = new RemoteConsumerRegistration();
		
		ProducerImpl producer;
		try
		{
			String serviceInstanceId = source.getDouiContext().getRequest().getServiceInstanceConfig().getId();
			producer = (ProducerImpl) ManagerFactory.getEntityManager().createNamedQuery(ProducerImpl.NAMED_QUERY_FIND_PRODUCER_BY_NAMESPACE)
																			.setParameter("namespace", serviceInstanceId)
																			.getSingleResult();
			producer.getRegistrations().add(registration);
			registration.setProducer(producer);
		}
		catch (NoResultException  e1) 
		{
			throw new PortalException(e1.getMessage(), getResource());
		}
		
		registration.setConsumerAgent(getParameter("consumerAgent", String.class));
		registration.setConsumerName(getParameter("consumerName", String.class));

		registration.setConsumerModes(WSRPUtils.join(Arrays.asList((String[])portletModes), ","));
		registration.setConsumerWindowStates(WSRPUtils.join(Arrays.asList((String[])windowStates), ","));
		
		Date date = getParameter("lifetimeTerminationTime", Date.class);
		LeaseTime lifetime = new LeaseTime();
		lifetime.setTerminationTime(WSRPUtils.toXMLGregorianCalendar(date));
		lifetime.setCurrentTime(WSRPUtils.toXMLGregorianCalendar(System.currentTimeMillis()));
		registration.setLifetime(lifetime);
		
		registration.setEnabled(true);
		registration.setMethodGetSupported(getParameter("supportsGetMethod", Boolean.class));
		
		ManagerFactory.getEntityManager().persist(registration);

		addDefaultResponse();
	}
}
